<template>
  <div class="workflow-start-page">
    <div class="page-header">
      <h2>发起流程</h2>
      <p>选择您要发起的流程，点击查看详情或直接发起</p>
    </div>

    <div class="process-grid">
      <div 
        v-for="process in processList" 
        :key="process.id" 
        class="process-card"
        v-auth="WorkflowAuth.PROCESS_START_DETAIL"
      >
        <div class="card-header">
          <h3>{{ process.processName }}</h3>
          <el-tag :type="getStatusType(process.status)">
            {{ getStatusText(process.status) }}
          </el-tag>
        </div>
        <div class="card-content">
          <p><strong>流程Key:</strong> {{ process.processKey }}</p>
          <p><strong>版本:</strong> {{ process.version }}</p>
        </div>
        <div class="card-actions">
          <el-button 
            type="primary" 
            @click="viewProcessDetail(process)"
            v-auth="WorkflowAuth.PROCESS_START_DETAIL"
          >
            查看详情
          </el-button>
          <el-button 
            type="success" 
            @click="handleStartProcessClick(process)"
            v-auth="WorkflowAuth.PROCESS_START_CREATE"
          >
            发起流程
          </el-button>
        </div>
      </div>
    </div>

    <!-- 流程详情弹窗 -->
    <ProcessDetailModal
      ref="processDetailModalRef"
      v-model:visible="detailModalVisible"
      :process-data="selectedProcess"
      mode="start"
      @start-process="handleStartProcess"
      @form-action="handleFormAction"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAuthorizedProcessList, startProcess as startProcessApi } from '@/api/workflow/process.api'
import ProcessDetailModal from '@/components/Workflow/ProcessDetailModal.vue'
import { WorkflowAuth } from '@/auth/workflow/workflow.auth'

// 引入统一的夜间模式样式
import '@/components/Workflow/styles/dark-theme.css'

const router = useRouter()
const processList = ref([])
const detailModalVisible = ref(false)
const selectedProcess = ref(null)
const processDetailModalRef = ref(null)

// 获取授权流程列表
async function fetchProcessList() {
  try {
    console.log('开始获取授权流程列表...')
    const response = await getAuthorizedProcessList()
    console.log('授权流程列表API响应:', response)
    
    // API直接返回数组数据，不需要response.data
    if (response && Array.isArray(response)) {
      processList.value = response
      console.log('设置流程列表:', processList.value)
    } else {
      console.log('API响应格式异常:', response)
      ElMessage.error('获取流程列表失败')
    }
  } catch (error) {
    console.error('获取流程列表失败:', error)
    ElMessage.error('获取流程列表失败')
  }
}

// 查看流程详情
function viewProcessDetail(process) {
  console.log('查看流程详情，流程数据:', process)
  selectedProcess.value = {
    ...process,
    id: process.id || process.processId, // 确保有id字段
    processVersionId: process.processVersionId // 添加流程版本ID
  }
  detailModalVisible.value = true
}

// 发起流程（直接点击按钮）
function handleStartProcessClick(process) {
  console.log('发起流程，流程数据:', process)
  selectedProcess.value = {
    ...process,
    id: process.id || process.processId, // 确保有id字段
    processVersionId: process.processVersionId // 添加流程版本ID
  }
  detailModalVisible.value = true
}

// 处理从ProcessDetailModal返回的发起流程结果
const handleStartProcess = (result) => {
  console.log('流程发起成功，结果:', result)
  detailModalVisible.value = false
  
  // 跳转到我的流程页面或刷新列表
  router.push('/workflow/myProcess')
}

// 生成业务Key
const generateBusinessKey = () => {
  const timestamp = Date.now()
  const random = Math.random().toString(36).substr(2, 9)
  return `WF_${timestamp}_${random}`
}

// 处理表单操作
const handleFormAction = (action, data) => {
  switch (action) {
    case 'preview':
      ElMessage.info('表单预览功能开发中')
      break
    case 'edit':
      ElMessage.info('表单编辑功能开发中')
      break
    case 'bind':
      ElMessage.info('表单绑定功能开发中')
      break
  }
}

// 获取状态类型
function getStatusType(status) {
  const statusMap = {
    'published': 'success',
    'draft': 'warning',
    'archived': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    'published': '已发布',
    'draft': '草稿',
    'archived': '已归档'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  fetchProcessList()
})
</script>

<style scoped>
.workflow-start-page {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
  font-size: 14px;
}

.process-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.process-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
}

.process-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.card-content {
  margin-bottom: 20px;
}

.card-content p {
  margin: 8px 0;
  color: #666;
  font-size: 14px;
}

.card-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.card-actions .el-button {
  flex: 1;
}

/* 夜间主题适配 */
:deep(.dark) .workflow-start-page {
  background: #1a1a1a;
}

:deep(.dark) .page-header h2 {
  color: #ffffff;
}

:deep(.dark) .page-header p {
  color: #b0b0b0;
}

:deep(.dark) .process-card {
  background: #2a2a2a;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  border: 1px solid #333;
}

:deep(.dark) .process-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5);
  border-color: #444;
}

:deep(.dark) .card-header h3 {
  color: #ffffff;
}

:deep(.dark) .card-content p {
  color: #b0b0b0;
}

:deep(.dark) .card-content strong {
  color: #ffffff;
}

/* 使用htmlRoot选择器的夜间主题适配 */
#htmlRoot[data-theme='dark'] .workflow-start-page {
  background: #1a1a1a;
}

#htmlRoot[data-theme='dark'] .page-header h2 {
  color: #ffffff;
}

#htmlRoot[data-theme='dark'] .page-header p {
  color: #b0b0b0;
}

#htmlRoot[data-theme='dark'] .process-card {
  background: #2a2a2a;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  border: 1px solid #333;
}

#htmlRoot[data-theme='dark'] .process-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5);
  border-color: #444;
}

#htmlRoot[data-theme='dark'] .card-header h3 {
  color: #ffffff;
}

#htmlRoot[data-theme='dark'] .card-content p {
  color: #b0b0b0;
}

#htmlRoot[data-theme='dark'] .card-content strong {
  color: #ffffff;
}
</style> 